package com.freesky.web.manager.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.freesky.common.dao.entity.Permission;
import com.freesky.common.dao.entity.Role;
import com.freesky.common.dao.entity.RolePerm;
import com.freesky.common.dao.entity.User;
import com.freesky.common.dao.mapper.UserMapper;
import com.freesky.common.enums.ResponseEnum;
import com.freesky.common.exception.EMallException;
import com.freesky.common.pojo.DataTablesResult;
import com.freesky.common.utils.reponse.JSONResponse;
import com.freesky.common.utils.reponse.JSONResponseDiretor;
import com.freesky.web.manager.service.UserService;
import com.freesky.web.manager.shiro.MyPasswordEncrypt;
import com.freesky.web.manager.util.ShiroUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

/**
 * @author Freesky
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public Set<String> getRoles(String username) {
        return userMapper.getRoles(username);
    }

    @Override
    public Set<String> getPermissions(String username) {
        return userMapper.getPermissions(username);
    }

    @Override
    public DataTablesResult getRoleList() {

        DataTablesResult result = new DataTablesResult();
        List<Role> roleList = new Role().selectAll();
        if (roleList == null) {
            throw new EMallException("获取角色列表失败");
        }
        result.setData(roleList);
        return result;
    }

    @Override
    public JSONResponse getAllRoles() {
        List<Role> list = new Role().selectAll();
        if (list == null) {
            throw new EMallException("获取所有角色列表失败");
        }
        return JSONResponseDiretor.buildSuccessJSONResponse(list);
    }

    @Override
    public JSONResponse addRole(Role role) {

        if (getRoleByRoleName(role.getName()) != null) {
            throw new EMallException("该角色名已存在");
        }
        if (!role.insert()) {
            throw new EMallException("添加角色失败");
        }
        if (role.getRoles() != null) {
            Role newRole = getRoleByRoleName(role.getName());
            for (int i = 0; i < role.getRoles().length; i++) {
                RolePerm rolePerm = new RolePerm();
                rolePerm.setRoleId(newRole.getId());
                rolePerm.setPermissionId(role.getRoles()[i]);
                if (!rolePerm.insert()) {
                    throw new EMallException("添加角色-权限失败");
                }
            }
        }
        return JSONResponseDiretor.buildSuccessJSONResponse(null);
    }

    @Override
    public Role getRoleByRoleName(String roleName) {
        return new Role().selectOne(new EntityWrapper().eq("name", roleName));
    }

    @Override
    public boolean getRoleByEditName(int id, String roleName) {

        Role role = new Role(id);
        role = role.selectById();
        Role newRole = null;
        if (role == null) {
            throw new EMallException("通过ID获取角色失败");
        }
        if (!role.getName().equals(roleName)) {
            newRole = getRoleByRoleName(roleName);
        }
        if (newRole == null) {
            return true;
        }
        return false;
    }

    @Override
    public JSONResponse updateRole(Role role) {

        if (!getRoleByEditName(role.getId(), role.getName())) {
            throw new EMallException("该角色名已存在");
        }
        if (!role.updateById()) {
            throw new EMallException("更新角色失败");
        }
        if (role.getRoles() != null) {
            //删除已有角色-权限
            List<RolePerm> list = new RolePerm().selectList(new EntityWrapper().eq("role_id", role.getId()));
            if (list != null) {
                for (RolePerm rolePerm : list) {
                    if (!rolePerm.deleteById()) {
                        throw new EMallException("删除角色权限失败");
                    }
                }
            }
            //新增
            for (int i = 0; i < role.getRoles().length; i++) {
                RolePerm rolePerm = new RolePerm();
                rolePerm.setRoleId(role.getId());
                rolePerm.setPermissionId(role.getRoles()[i]);

                if (!rolePerm.insert()) {
                    throw new EMallException("编辑角色-权限失败");
                }
            }
        } else {
            List<RolePerm> list = new RolePerm().selectList(new EntityWrapper().eq("role_id", role.getId()));
            if (list != null) {
                for (RolePerm rolePerm : list) {
                    if (!rolePerm.deleteById()) {
                        throw new EMallException("删除角色权限失败");
                    }
                }
            }
        }
        return JSONResponseDiretor.buildSuccessJSONResponse(null);
    }

    @Override
    public int deleteRole(int id) {
        //判断是否有用户使用该角色
        User one = new User().selectOne(new EntityWrapper().eq("role_id", id));
        if (one != null) {
            return JSONResponseDiretor.buildErrorJSONResponse(ResponseEnum.ROLE_IN_USE, null).getCode();
        }
        Role role = new Role(id);
        if (!role.deleteById()) {
            throw new EMallException("删除角色失败");
        }
        boolean deleteRolePerm = new RolePerm().delete(new EntityWrapper().eq("role_id", id));
        if (!deleteRolePerm) {
            throw new EMallException("删除角色权限失败");
        }
        return 1;
    }

    @Override
    public JSONResponse countRole() {
        return JSONResponseDiretor.buildSuccessJSONResponse(new Role().selectCount(new EntityWrapper()));
    }

    @Override
    public JSONResponse getPermissionList() {
        DataTablesResult result = new DataTablesResult();
        List<Permission> list = new Permission().selectAll();
        if (list == null) {
            throw new EMallException("获取权限列表失败");
        }
        result.setSuccess(true);
        result.setData(list);
        return JSONResponseDiretor.buildSuccessJSONResponse(result);
    }


    @Override
    public JSONResponse countPermission() {
        return JSONResponseDiretor.buildSuccessJSONResponse(new Permission().selectCount(new EntityWrapper()));
    }

    @Override
    public DataTablesResult getUserList() {

        DataTablesResult result = new DataTablesResult();
        List<User> list = new User().selectAll();
        if (list == null) {
            throw new EMallException("获取用户列表失败");
        }
        for (User user : list) {
            String names = "";
            Iterator it = getRoles(user.getUsername()).iterator();
            while (it.hasNext()) {
                names += it.next() + " ";
            }
            user.setPassword("");
            user.setRoleNames(names);
        }
        result.setData(list);
        return result;
    }


    @Override
    public boolean getUserByName(String username) {
        User one= new User().selectOne(new EntityWrapper().eq("username",username));
        if (one != null) {
            return false;
        }
        return true;
    }

    @Override
    public boolean getUserByPhone(String phone) {
        User one= new User().selectOne(new EntityWrapper().eq("phone",phone));
        if (one != null) {
            return false;
        }
        return true;
    }

    @Override
    public boolean getUserByEmail(String email) {
        User one= new User().selectOne(new EntityWrapper().eq("email",email));
        if (one != null) {
            return false;
        }
        return true;
    }

    @Override
    public JSONResponse addUser(User user) {
        ShiroUtil.volidateAuth("userAdd");
        if (!getUserByName(user.getUsername())) {
            throw new EMallException("用户名已存在");
        }
        if (!getUserByPhone(user.getPhone())) {
            throw new EMallException("手机号已存在");
        }
        if (!getUserByEmail(user.getEmail())) {
            throw new EMallException("邮箱已存在");
        }
        user.setPassword(MyPasswordEncrypt.encryptPassword(user.getPassword()));
        user.setState(1);
        user.setCreated(new Date());
        user.setUpdated(new Date());
        if (! user.insert()) {
            throw new EMallException("添加用户失败");
        }
        return JSONResponseDiretor.buildSuccessJSONResponse(null);
    }

    @Override
    public User getUserById(Long id) {
        User user = new User(id).selectById();
        if (user == null) {
            throw new EMallException("通过ID获取用户失败");
        }
        user.setPassword("");
        return user;
    }

    @Override
    public JSONResponse updateUser(User user) {
        ShiroUtil.volidateAuth("userUpdate");
        User old = new User(user.getId()).selectById();
        user.setPassword(old.getPassword());
        user.setState(old.getState());
        user.setCreated(old.getCreated());
        user.setUpdated(new Date());
        if (!user.updateById()) {
            throw new EMallException("更新用户失败");
        }
        return JSONResponseDiretor.buildSuccessJSONResponse(null);
    }

    @Override
    public JSONResponse changeUserState(Long id, int state) {

        User user = new User(id).selectById();
        user.setState(state);
        user.setUpdated(new Date());
        if (!user.updateById()) {
            throw new EMallException("更新用户状态失败");
        }
        return JSONResponseDiretor.buildSuccessJSONResponse(null);
    }

    @Override
    public JSONResponse changePassword(User user) {

        User old =new User(user.getId()).selectById();
        old.setUpdated(new Date());
        user.setPassword(MyPasswordEncrypt.encryptPassword(user.getPassword()));
        if (!user.updateById()) {
            throw new EMallException("修改用户密码失败");
        }
        return JSONResponseDiretor.buildSuccessJSONResponse(null);
    }

    @Override
    public boolean getUserByEditName(Long id, String username) {

        User user = getUserById(id);
        boolean result = true;
        if (user.getUsername() == null || !user.getUsername().equals(username)) {
            result = getUserByName(username);
        }
        return result;
    }

    @Override
    public boolean getUserByEditPhone(Long id, String phone) {

        User user = getUserById(id);
        boolean result = true;
        if (user.getPhone() == null || !user.getPhone().equals(phone)) {
            result = getUserByPhone(phone);
        }
        return result;
    }

    @Override
    public boolean getUserByEditEmail(Long id, String email) {

        User user = getUserById(id);
        boolean result = true;
        if (user.getEmail() == null || !user.getEmail().equals(email)) {
            result = getUserByEmail(email);
        }
        return result;
    }

    @Override
    public int deleteUser(Long userId) {
        if (! new User(userId).deleteById()) {
            throw new EMallException("删除用户失败");
        }
        return 1;
    }

    @Override
    public JSONResponse countUser() {
        return JSONResponseDiretor.buildSuccessJSONResponse(new User().selectCount(new EntityWrapper()));
    }

    @Override
    public JSONResponse getPermsByRoleId(Integer roleId) {
        List<String> perms = userMapper.getPermsByRoleId(roleId);
        return JSONResponseDiretor.buildSuccessJSONResponse(perms);
    }

}
